import { Component, OnInit } from '@angular/core';
import { LoginService } from '../../shared/service/login.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-sign',
  templateUrl: './sign.component.html',
  styleUrls: ['./sign.component.scss']
})
export class SignComponent implements OnInit {

  phone: any;
  password: any;

  loading: Boolean = false;

  error: String = '';

  constructor(
    private loginService: LoginService,
    private router: Router
  ) {
    this.phone = '';
    this.password = '';
  }

  ngOnInit() {
    // 默认登陆
    this.defaultSign();
  }

  /*****
  *  默认登陆
  *  @param  :  (参数)
  *  @return :  (返回值说明)
  *****/
  defaultSign() {
    const param = JSON.parse(localStorage.getItem('KA-U'));
    if (param) {
      this.loading = true;
      this.linkService(param);
    }
  }

  /*****
  *  登陆验证
  *  @param  :  (参数)
  *  @return :  (返回值说明)
  *****/
  loadSign() {
    const param = {
      phone: this.phone,
      password: this.password
    };
    this.linkService(param);
  }

  /*****
  *  LINK SERVICE
  *  @param  :  (参数)
  *  @return :  (返回值说明)
  *****/
  linkService(param) {
    this.loginService.login(param)
        .then((res) => {
          switch (res['state']) {
            case 200:
              this.error = '登陆成功';
              // 登陆信息处理过后 写入 本地存储
              localStorage.setItem('KA-U', JSON.stringify(res['data']));
              // 服务里设置用户信息
              this.loginService.serviceSetUserData(res['data']);
              // 路由跳转到主界面
              this.router.navigateByUrl('/warpper');
            break;
            case 400:
              this.error = res['error'];
              this.password = '';
            break;
            case 404:
              this.error = res['error'];
              this.password = '';
              this.phone = '';
            break;
          }

          this.loading = false;

        });
  }
}
